//
//  MyViewController.m
//  DailyNews
//
//  Created by 于跃隆 on 2018/12/21.
//  Copyright © 2018年 于跃隆. All rights reserved.
//

#import "MyViewController.h"
#import "NewsTableViewCell.h"
#import "CollectionHandle.h"
#import "HttpHandle.h"
#import "NewsDetailViewController.h"

@interface MyViewController ()<UITableViewDelegate , UITableViewDataSource>
@property (nonatomic , strong) UITableView *tbv;
@property (nonatomic , strong) NSMutableArray *datasource;

@end

@implementation MyViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _datasource = [[CollectionHandle sharedDBManager] fetchAll];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.datasource = [[NSMutableArray alloc] init];
    
    [self.view addSubview:self.tbv];
    [self.tbv registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:nil] forCellReuseIdentifier:@"NewsCell"];
    
    self.navigationItem.title = @"我的收藏";
    
    [self addData];
}
-(void)addData{
    HttpHandle *http = [[HttpHandle alloc] init];
    [[CollectionHandle sharedDBManager] insertModel:http];
    [self.tbv reloadData];
}
- (UITableView *)tbv{
    if (!_tbv) {
        _tbv = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tbv.delegate = self;
        _tbv.dataSource = self;
    }
    return _tbv;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _datasource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
    if (self.datasource.count>0) {
        HttpHandle *http = _datasource[indexPath.row];
        [cell setValueForCellModel:http];
    }
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NewsDetailViewController *detail = [[NewsDetailViewController alloc] init];
    HttpHandle *http = _datasource[indexPath.row];
    detail.pathUrl = http.url;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    HttpHandle *http= _datasource[indexPath.row];
    [[CollectionHandle sharedDBManager] deleteModelByName:http.author_name];
    [_datasource removeObject:_datasource[indexPath.row]];
    [self.tbv reloadData];
}

@end
